package reflect.engine;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import object.model.JavaFile;
import object.model.JavaVariables;
import object.model.MySQLData;
import object.model.MySQL_TableDDL;
import object.model.MySQL_TableDesc;
import object.model.TableType;
import reflect.filew.JavaFileWritter;
import system.Sys_Config;
import system.mysql.schema.information.models.TABLES;
import system.parser.Sys_SQL2JavaTypeParser;
import system.queryer.MySQL_Queryer;

class ObjectReverseFactory {
	
	private MySQL_Queryer mysqlQ = new MySQL_Queryer();
	private JavaFileWritter jfw = new JavaFileWritter();
	private Sys_SQL2JavaTypeParser p = new Sys_SQL2JavaTypeParser();
	private JavaModelAnalyser jma = new JavaModelAnalyser();
	
	public void formDataBase(){
		List<MySQL_TableDDL> ddlList = new ArrayList<MySQL_TableDDL>();
		ddlList.addAll(jma.reverseTableModelDDL());
		ddlList.addAll(jma.reverseViewModelDDL());
		for(int i=0;i<ddlList.size();i++){
			MySQL_TableDDL item = ddlList.get(i);
			System.out.print("("+(i+1)+"/"+ddlList.size()+")Push: " + item.getTable());
			try {
				this.mysqlQ.toUpdate(item.getDropStatement());
				this.mysqlQ.toUpdate(item.getCreateTable());				
				System.out.println(" SUCCESS");
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				System.out.println(" FAILED->Msg:" + e.getMessage());
				//System.out.println(item.getCreateTable());
			}
		}
		System.out.println("FINISHED!");
	}
	
	public void formJavaFile(){
		List<TABLES> tbL = new DataBaseStructInfoer().getAllTables();
		int i = 0;
		for(;i<tbL.size();i++){			
			try{
				TABLES tb = tbL.get(i);
				List<MySQL_TableDesc> tbDL = new DataBaseStructInfoer().getTableDesc(tb.getTABLE_NAME());
				JavaFile jf = this.formJavaFile(tb.getTABLE_NAME(),tbDL, TableType.valueOfDesc(tb.getTABLE_TYPE()));
				jfw.toWriteJavaFile(jf);
				System.out.println("Table: "+ tb.getTABLE_NAME() +" Transfered");
			}catch(Exception e){
				e.printStackTrace();
			}			
		}
		System.out.println("OK! ("+i+"/"+tbL.size()+")");
	}

	private JavaFile formJavaFile(String tbName,List<MySQL_TableDesc> tb, TableType type){
		List<JavaVariables> vars = new ArrayList<JavaVariables>();
		new DataBaseStructInfoer();
		for(int i=0;i<tb.size();i++){
			MySQL_TableDesc tbI = tb.get(i);
			JavaVariables var = p.parse(tbI);
			vars.add(var);
		}
		JavaFile jf = new JavaFile(Sys_Config.JAVA_MODEL_PACKAGE, tbName, vars, type);
		return jf;
	}
}
